import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    const res = response.data

    // 如果响应中包含code字段，统一处理
    if (res.code && res.code !== 200) {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }

    return res
  },
  error => {
    console.error('API请求错误:', error)

    let message = '网络错误'
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = '请求参数错误'
          break
        case 401:
          message = '未授权访问'
          break
        case 403:
          message = '禁止访问'
          break
        case 404:
          message = '请求资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = error.response.data?.detail || '请求失败'
      }
    } else if (error.request) {
      message = '网络连接失败'
    }

    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 导入API模块
import { taskApi as taskApiModule } from './tasks'
import { repositoryApi as repositoryApiModule } from './repositories'
import { executionApi as executionApiModule } from './executions'
import { fileApi as fileApiModule } from './files'
import { logApi as logApiModule } from './logs'
import { systemApi as systemApiModule } from './system'

export default api

// 导出API，支持多种命名方式
export const tasksApi = taskApiModule
export const taskApi = taskApiModule

export const repositoriesApi = repositoryApiModule
export const repositoryApi = repositoryApiModule

export const executionsApi = executionApiModule
export const executionApi = executionApiModule

export const filesApi = fileApiModule
export const fileApi = fileApiModule

export const logsApi = logApiModule
export const logApi = logApiModule

export const systemApi = systemApiModule